/*
 * @Description:
 * @version:
 * @Author: 尹鹏孝
 * @Date: 2023-08-04 21:31:18
 * @LastEditors: 尹鹏孝
 * @LastEditTime: 2023-10-23 21:58:51
 */
import { Injectable } from '@nestjs/common';
import { InjectRepository, } from '@nestjs/typeorm';
import { Repository, Like } from 'typeorm';
import { User } from '../entity/user.entity';
import { UserDetail } from '../entity/userDetail.entity';
import { PageInit, PageNation } from 'src/interface/page.interface';
type T = any;
@Injectable()
export class UsersService {

    constructor(
        @InjectRepository(User)
        private readonly userRepository: Repository<User>,
        @InjectRepository(UserDetail)
        private readonly userDetailRepository: Repository<UserDetail>,
    ) { }
    //创建用户
    async create(user: User): Promise<User> {
        return await this.userRepository.save(user);
    }
    async findOne(id: number, username: string): Promise<User> {
        console.log(id)
        console.log(username)
        return await this.userRepository.findOneBy({
            username: username,
            id: id
        });
    }

    async findAll(query: PageInit): Promise<PageNation> {
        //  console.log(query)
        const take = query.take || 10
        const skip = query.skip || 0
        const keyword = query.keyword || ''

        let res = await this.userRepository.findAndCount({
            where: { username: Like('%' + keyword + '%') }, order: { username: "DESC" },
            take: take,
            skip: skip
        })

        const [result, total] = res;
        console.log('输出res:', result.length)
        return {
            list: result,
            count: total
        }
    }


    async findBy(user: User): Promise<PageNation> {
        const res = await this.userRepository.findAndCountBy(user)
        const [result, total] = res;
        return {
            count: total,
            list: result
        };
    }
    async updateDetail(user: UserDetail): Promise<any> {
        console.log('输出：', user.id)
        const one = await this.userDetailRepository.findOneBy({
            id: user.id
        })
        console.log('输出one:', one)
        const res = await this.userDetailRepository.update(one, user)
        console.log('输出更新后结果：', res)
        return res;

    }
    //创建用户详情，通过t_sys_user表的id关联这里的user_id
    async createDetail(user: UserDetail): Promise<any> {
        try {
            if (typeof user.user_id === 'undefined') {
                return {
                    code: 500,
                    msg: '缺少user_id'
                }
                return
            }
            let one = (user?.user_id ?? null) && await this.userRepository.findOneBy({
                id: user.user_id
            })
            console.log('输出当前用户：', one)
            if (one === null) {
                return {
                    code: 500,
                    msg: '不存在user'
                }
            }
            //查询到了id：
            const oneNew = await this.userDetailRepository.findOneBy({
                user_id: one.id
            })
            if (oneNew) {
                console.log('oneNew.id：', oneNew)
                let newOne = { ...oneNew }
                newOne.username = user.username

                let keys = Object.keys(user);
                console.log('keys:', keys)

                for (let i = 0; i < keys.length; i++) {
                    let key = keys[i];
                    newOne[key] = user[key];
                }
                newOne.id = oneNew.id;
                newOne.user_id = oneNew.user_id;
                console.log('1111', oneNew)
                const res = await this.userDetailRepository.update({
                    id: oneNew.id,
                }, newOne)
                console.log('res:', res)
                if (res.affected) {
                    return {
                        code: 200,
                        msg: '修改成功'
                    }
                }
                return res;

            } else {
                let keys = Object.keys(user);
                let newOne={user_id:null,nick_name:'',age:null,gender:null,address:'',phone:''}
                console.log('keys:', keys)
                console.log('user:',user)
                for (let i = 0; i < keys.length; i++) {
                    let key = keys[i];
                    newOne[key] = user[key];
                }
                newOne.user_id = user.user_id;
                for (let i in newOne) {
                    if (newOne[i] === null || (typeof newOne[i] === 'undefined')) {
                         return {
                                code: 500,
                                msg: i+'不能为空'
                            }

                    }
                }
                const res = await this.userDetailRepository.save(newOne)
                return res;
            }

        } catch (error) {
            console.log(error)
            return {
                code: 500,
                msg: '创建失败'
            }
        }

    }

    async deleteUser(id): Promise<any> {
        try {
            let one = await this.userRepository.findOne({
                where: { id: id },
                withDeleted: true
            });
            let res = await this.userRepository.softDelete(one.id);
            console.log(res)
            //   let res = await this.userRepository.delete(one.id);
            //   console.log(res)
            return {
                code: 200,
                msg: '删除成功'
            }

        } catch (error) {
            console.log(error)
            return {
                code: 500,
                msg: '删除失败'
            }
        }
    }


    async findUserDetailByUserId(userId: number): Promise<UserDetail> {
    const user = await this.userRepository.findOne({ where: { id: userId }, relations: ['userDetail'] });
    return user ? user.userDetail : null;
  }
}
